﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Data.Common;

public partial class TranslationsExcel : System.Web.UI.Page
{
    private Database db = new Database();

    /// <summary>
    /// Datebinds the application CheckBoxList
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack) {
            using(Database.Command cmd = db.CreateCommand()) {
                cmd.CommandText = "SELECT id, displayname FROM applications ORDER BY name ASC";
                Database.DataAdapter adapter = new Database.DataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                chlApplication.DataSource = ds;
                chlApplication.DataValueField = "id";
                chlApplication.DataTextField = "displayname";
                chlApplication.DataBind();
                if(chlApplication.Items.Count > 0) {
                    ShowLanguages(null, EventArgs.Empty);
                    mltMain.ActiveViewIndex = 1;
                }
            }
            Page.ClientScript.RegisterStartupScript(typeof(Page), "postbackfix", @"
                var __oldAction = theForm.action;
                var __oldPostBack = __doPostBack;
                __doPostBack = function(eventTarget, eventArgument) {
                    theForm.action = __oldAction;
                    __oldPostBack(eventTarget, eventArgument);            
                }", true);
        }
    }

    /// <summary>
    /// Shows the languages and bundles for the application selected.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ShowLanguages(object sender, EventArgs e) {
        lstLanguages.Items.Clear();
        lstBundles.Items.Clear();
        if(chlApplication.SelectedValue == null) {
            return;
        }
        db.OpenConnection();
        using(Database.Command cmd = db.CreateCommand()) {
            cmd.AddParameterWithValue("@id", "");
            DbDataReader reader;
            ListComparer cmp = new ListComparer(); 
            List<string> languages = new List<string>(),
                         bundles = new List<string>();
            string[] langs;
            List<ListItem> tempLanguages = new List<ListItem>(),
                           tempBundles = new List<ListItem>();
            foreach(ListItem itm in chlApplication.Items) {
                if(itm.Selected) {
                    cmd.Parameters["@id"].Value = itm.Value;
                    cmd.CommandText = "SELECT languages FROM applications WHERE id = @id";
                    reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
                    while(reader.Read()) {
                        langs = reader["languages"].ToString().Trim().Split(',');
                        foreach(string lang in langs) {
                            if(!languages.Contains(lang)) {
                                languages.Add(lang);
                            }
                        }
                    }
                    reader.Close();

                    cmd.CommandText = "SELECT id, name FROM bundles WHERE application = @id";
                    reader = cmd.ExecuteReader();
                    while(reader.Read()) {
                        ListItem itmBundle = new ListItem(reader["name"].ToString(), reader["id"].ToString());
                        itmBundle.Selected = true;
                        tempBundles.Add(itmBundle);
                    }
                    reader.Close();
                }
            }
            foreach(string abbrev in languages) {
                ListItem itm = null;
                try {
                    itm = new ListItem(CultureInfo.GetCultureInfo(abbrev).EnglishName, abbrev);
                } catch {
                    itm = new ListItem(abbrev);
                }
                itm.Selected = true;
                tempLanguages.Add(itm);
            }
            tempLanguages.Sort(cmp);
            lstLanguages.Items.AddRange(tempLanguages.ToArray());
            if(lstLanguages.Items.Count == 0) {
                ListItem itm = new ListItem("No languages found", "");
                itm.Selected = true;
                lstLanguages.Items.Add(itm);
                lstLanguages.Enabled = false;
            } else {
                lstLanguages.Enabled = true;
            }

            tempBundles.Sort(cmp);
            lstBundles.Items.AddRange(tempBundles.ToArray());
            if(lstBundles.Items.Count == 0) {
                ListItem itm = new ListItem("No bundles found", "");
                itm.Selected = true;
                lstBundles.Items.Add(itm);
                lstBundles.Enabled = false;
            } else {
                lstBundles.Enabled = true;
            }
        }
    }

    /// <summary>
    /// Forwards the request to the spreadsheet generator. Using the postback URL property interferes with AJAX.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnToExcel_Click(object sender, EventArgs e) {
        Response.Redirect("Excel.aspx");
    }
}
